package jmu.zzh.alumnus.common.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@ConditionalOnProperty(name = "jwt-secret-key")
public class CustomJWTUtils {
    private static final Logger log = LoggerFactory.getLogger(CustomJWTUtils.class);

    @Value("${jwt-secret-key}")
    public String key;

    public String createToken(String username, String password, Long userId) {
        Map<String, Object> payload = new HashMap<>();

        // 业务内容
        payload.put("username", username);
        payload.put("password", password);
        payload.put("userId", userId);

        // 使用时间戳
        long currentTimeMillis = System.currentTimeMillis();
        long expTimeMillis = currentTimeMillis + 24 * 60 * 60 * 1000; // 24小时后过期

        payload.put(JWTPayload.ISSUED_AT, currentTimeMillis / 1000);  // 转换为秒
        payload.put(JWTPayload.EXPIRES_AT, expTimeMillis / 1000);     // 转换为秒
        payload.put(JWTPayload.NOT_BEFORE, currentTimeMillis / 1000); // 转换为秒

        String token = JWTUtil.createToken(payload, key.getBytes());
        log.info("生成 JWT token = {}, username = {}, userId = {}", token, username, userId);

        return token;
    }

    public boolean validate(String token) {
        try {
            JWT jwt = JWTUtil.parseToken(token).setKey(key.getBytes());
            // 验证签名
            boolean validateSign = jwt.verify();
            // 验证时间
            boolean validateTime = jwt.validate(0);
            
            log.info("JWT token 签名验证结果 = {}, 时间验证结果 = {}", validateSign, validateTime);
            
            return validateSign && validateTime;
        } catch (Exception e) {
            log.error("JWT token 验证异常", e);
            return false;
        }
    }

    public JSONObject getJSONObject(String token) {
        try {
            JWT jwt = JWTUtil.parseToken(token).setKey(key.getBytes());
            JSONObject payloads = jwt.getPayloads();

            // 返回给前端之前，删除额外增加的几个时间值
            payloads.remove(JWTPayload.ISSUED_AT);
            payloads.remove(JWTPayload.EXPIRES_AT);
            payloads.remove(JWTPayload.NOT_BEFORE);

            log.info("从 JWT token 中获取的原始内容 = {}", payloads);
            return payloads;
        } catch (Exception e) {
            log.error("JWT token 解析异常", e);
            return null;
        }
    }

    public String getUsernameFromToken(String token) {
        JSONObject jsonObject = getJSONObject(token);
        return jsonObject != null ? jsonObject.getStr("username") : null;
    }

    public Long getUserIdFromToken(String token) {
        JSONObject jsonObject = getJSONObject(token);
        return jsonObject != null ? jsonObject.getLong("userId") : null;
    }
}
